package com.java.base.exercise.current;

import lombok.SneakyThrows;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @Author RenPu
 * @Date 2023/3/14 16:39
 * @Version 1.0
 * @Description: 基于AQS实现自定义的CountDownLatch计算器
 **/
public class RenPuCountDownLatch {

    private Sync sync;

    public RenPuCountDownLatch(int sync) {
        this.sync =new Sync(sync) ;
    }


    public void countDown(){
        sync.releaseShared(1);
    }

    public void await(){
        sync.acquireShared(1);
    }


    class Sync extends AbstractQueuedSynchronizer{

        private int permist;

        public Sync(int permist) {
            setState(permist);
        }


        @Override
        protected int tryAcquireShared(int i) {
            return getState()==0?1:-1;
        }

        @Override
        protected boolean tryReleaseShared(int i) {
            while (true){
                int state = getState();
                if(state==0){
                    return false;
                }
                int nextInt=state-1;
                if(compareAndSetState(state,nextInt)){
                   return nextInt==0;
                }
            }
        }


    }







    @SneakyThrows
    public static void main(String[] args) {

//        CountDownLatch countDownLatch = new CountDownLatch(6);

        RenPuCountDownLatch countDownLatch=new RenPuCountDownLatch(6);


        for (int i = 0; i <6 ; i++) {
            int index=i;
            new Thread(()->{
                System.out.println("开始准备。。start。。。"+index);
                countDownLatch.countDown();
            }).start();

            Thread.sleep(1000L);


        }
        countDownLatch.await();


        System.out.println("一起实现财富自由。。struggling。。");

    }




}
